﻿using Cxuu.Common;
using Cxuu.Models;
using Cxuu.Service;
using Cxuu.Web.Authorize;
using Cxuu.Web.Hubs;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using PetaPoco;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Cxuu.Web.Admin
{
    [Area("Admin")]
    [Authorize]
    public class NoticeController : Base
    {
        private readonly LoginUtil _LoginUtil;
        private readonly NoticeKeyService _notice;
        private readonly ConfigService _configService;
        private readonly AttmentService _attment;
        private readonly AdminUserService _user;
        private readonly LogService _logService;
        private readonly MessageHub _messageHub;
        public NoticeController(LoginUtil LoginUtil,
            AdminUserService adminUserService,
            LogService logService,
            AttmentService attmentService,
            ConfigService configService,
            NoticeKeyService noticeKeyService, MessageHub messageHub
            )
        {
            _LoginUtil = LoginUtil;
            _notice = noticeKeyService;
            _user = adminUserService;
            _configService = configService;
            _logService = logService;
            _attment = attmentService;
            _messageHub = messageHub;
        }

        [HttpGet]
        [ActionPermissionFilter(Permission = PermissionKeys.Notice_Index)]
        public async Task<IActionResult> IndexAsync([FromQuery] NoticeQuery query, int viewpost = 0)
        {
            if (query.Json == 1)
            {
                query.Uid = await _LoginUtil.LoginUserId();
                Page<ViewNotice> list = await _notice.GetPageListAsync(query);
                return Json(new { code = 0, data = list.Items, count = list.TotalItems });
            }
            if (viewpost == 0)
                return View();
            else if (viewpost == 1)
                return View("IndexPost");
            else
                return View("ReadList");//viewpost=2
        }

        [HttpGet, ActionName("Read")]
        [ActionPermissionFilter(Permission = PermissionKeys.Notice_Index)]
        public async Task<IActionResult> ReadAsync(int id, int noticeId)
        {
            UserInfo adminUser = await _LoginUtil.UserInfoAsync();
            ViewNotice notice = await _notice.ReadAsync(id, noticeId, adminUser);
            List<ViewAttment> attments = null;
            if (!string.IsNullOrEmpty(notice.Att))
                attments = await _attment.GetListAsync(notice.Att);
            ViewBag.attments = attments;
            return View(notice);
        }
        [HttpGet]
        [ActionPermissionFilter(Permission = PermissionKeys.Notice_AddOrEdit)]
        public async Task<IActionResult> AddOrEditAsync(int jsonUser)
        {
            if (jsonUser == 1)
            {
                int userId =await _LoginUtil.LoginUserId();
                List<UserIdAndName> adminUsers = await _user.GetNameAsync(userId);
                return Json(new { code = 0, data = adminUsers });
            }
            //附件信息
            SytemConfig configSiteInfo = await _configService.GetByNameAsync();
            ViewBag.fileExts = configSiteInfo.FileExt;
            ViewBag.fileSize = configSiteInfo.FileSize;
            return View();
        }

        [HttpPost, ActionName("CreatePost")]
        [XssFieldFilter]//防Xss
        [ActionPermissionFilter(Permission = PermissionKeys.Notice_AddOrEdit)]
        [Log(Name = "发布消息")]
        public async Task<IActionResult> CreatePostAsync(EditNotice notice)
        {
            if (ModelState.IsValid)
            {
                UserAction user = _LoginUtil.UserAction();
                await _notice.InsertAsync(notice, user.UserId);
                return Json(new { status = 1, msg = "消息发布 目标ID：" + notice.GetUid });
            }
            else
            {
                var error = ModelState.GetErrorMessages();
                return Json(new { status = 0, msg = error });
            }
        }
        /// <summary>
        /// 发送通知公告表
        /// </summary>
        /// <returns></returns>
        [ActionPermissionFilter(Permission = PermissionKeys.Notice_AddOrEdit)]
        public async Task<IActionResult> SendNoticeAsync(int noticeId = 0)
        {
            if (noticeId <= 0)
            {
                return Json(new { status = 0, msg = "请求实体为空" });
            }
            ViewNotice response = await _notice.ReadOneAsync(noticeId);
            if (response != null)
            {
                await _messageHub.Clients.All.SendAsync(HubsConstant.ReceiveNotice, response.Title, response.Content);
            }
            return Json(new { status = 1, msg = "发送成功！" });
        }
        [HttpPost]
        [ActionPermissionFilter(Permission = PermissionKeys.Notice_Delete)]
        [Log(Name = "删除消息")]
        public async Task<IActionResult> Delete(int id)
        {
            if (await _notice.DeleteByPriKeyAsync(id) > 0)
            {
                return Json(new { status = 1, msg = "删除消息 ID：" + id });
            }
            else
                return Json(new { status = 0, msg = "删除失败 ID：" + id });
        }




    }
}
